<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
    <!-- 引入Vue 全局注册一个名为Vue的构造函数 -->
    <script src="../js/vue.js"></script>
    <title>Vue的监听属性</title>
  </head>

  <!-- 总结computed能完成的，watch都可以完成，但watch能完成的computed不一定能完成，例如异步操作 -->
  <!-- 所有被vue管理的函数最好写成普通函数，这样this的指向才能是vm -->
  <!-- 所有不被vue管理的函数最好写成箭头函数，(定时器的回调函数，ajax的回调函数) -->
  <body>
    <!-- 异步的计算推荐用watch -->
    <div id="root1">
      <h2>今天天气很{{info}}</h2>
      <button @click="judge=!judge">切换天气</button><br />
      <span>{{numbers.a}}</span>
      <button @click="add">点我让a+1</button><br />
      <span>{{numbers.b}}</span>
      <button @click="addb">点我让b+1</button>
      <button @click="numbers={a:66,b:88}">彻底替换掉numbers</button><br />
      姓：<input type="text" v-model="firstname" /><br />
      名: <input type="text" v-model="lastname" /><br />
      姓名：<span>{{fullName}}</span>
    </div>

    <script>
      let vm = new Vue({
        el: "#root1",
        data: {
          firstname: "张三",
          lastname: "李四",
          fullName: "",
          judge: true,
          numbers: {
            a: 1,
            b: 2,
          },
        },
        methods: {
          add() {
            this.numbers.a++;
          },
          addb() {
            this.numbers.b++;
          },
        },
        computed: {
          info() {
            return this.judge ? "炎热" : "寒冷";
          },
        },
        watch: {
          // immediate:true,//初始化时让handler调用一下
          // judge:{
          //     handler(newValue,oldValue){
          //         console.log("judge的属性值变了",newValue,oldValue);
          //     }
          // },
          //简写
          // judge(newValue,oldValue){
          //     console.log("judge改变了",newValue,oldValue);
          // },
          "numbers.a": {
            handler(newValue, oldValue) {
              console.log("a的值已经被修改了", newValue, oldValue);
            },
          },
          numbers:{
              deep:true,
              handler(){

                console.log("numbers的值已经被修改了");
              }
            },
          firstname(newValue, oldValue) {
            console.log("姓改变了");
            setTimeout(() => {
              this.fullName = newValue + this.lastname;
            }, 1000);
          },
          lastname(newValue, oldValue) {
            this.fullName = this.firstname + newValue;
          },
        },
      });
      // vm.$watch('judge',{
      //     handler(newValue,oldValue){
      // console.log("judge的属性值变了",newValue,oldValue);
      //     }
      // })

      //简写
      // vm.$watch("judge",function(newValue,oldValue){
      //  console.log("judge的值改变成功")
      // })
    </script>
  </body>
</html>
